package com.zhongxi.guoyuan.view;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.libs.zxing.CaptureActivity;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhongxi.guoyuan.fragment.MainPersonFragment;
import com.zhongxi.guoyuan.OffLineShop.UI.OffLineShopDetailActivtiy;
import com.zhongxi.guoyuan.OffLineShop.UI.PayMoneyActivity;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.UpdateResult;
import com.zhongxi.guoyuan.entity.ad.AdData;
import com.zhongxi.guoyuan.entity.ad.AdResult;
import com.zhongxi.guoyuan.entity.consumerYield.TodayConsumerYield;
import com.zhongxi.guoyuan.entity.user.TodayEarningResult;
import com.zhongxi.guoyuan.entity.user.center.MyInfo;
import com.zhongxi.guoyuan.entity.user.center.NewMessage;
import com.zhongxi.guoyuan.entity.user.center.UserExtendResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.DataUtil;
import com.zhongxi.guoyuan.utils.DeviceUtils;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.LunBoUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.beautifulStore.ProjectDetailActivity;
import com.zhongxi.guoyuan.view.beautifulStore.StoreDetailActivity;
import com.zhongxi.guoyuan.view.personalCenter.ClearWeedDetailActivity;
import com.zhongxi.guoyuan.view.personalCenter.SystemMessageActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinDetailActivity;
import com.zhongxi.guoyuan.view.rewardCoin.RewardCoinShoperAtivity;
import com.zhongxi.guoyuan.view.seller.SellerCenterActivity;
import com.zhongxi.guoyuan.view.seller.offline.AddParameter;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.view.user.MyDividendActivity;
import com.zhongxi.guoyuan.view.user.gift.GiftDetailActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;


public class MainHomeActivity extends BaseActivity implements View.OnClickListener, OnBannerListener {

    private static final int MAINHOMEPAYMONEY = 88;
    private List<AdData> data = new ArrayList<AdData>();
    //    private TextView ivLocation;
    //   private ImageView ivDial;
    private LinearLayout meibiShop;
    private LinearLayout bolivarShop;
    private TextView tvStoreHome;
    private String flag;

    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;
    private TextView tvNewTips;
    private FrameLayout flow;
    /**
     * 分红点数
     */
    private RelativeLayout title;
    private RelativeLayout rl_content;
    private ImageView iv_service;
    private ImageView iv_unread_dot;
    private PopupWindow pw;
    private int count;
    private LinearLayout llUpGift;
    private ProgressDialog mDialog;
    private UpdateResult result;
    private AlertDialog dialog;
    private Banner banner;
    public static final int requestFulshConver = 66;
    private TextView tvAd;
    private LinearLayout ll_yield_contain;
    private RelativeLayout rl_pricilege;
    private TextView tv_original;
    private RelativeLayout rl_yield;
    private TextView tv_today;
    private TextView tv_privilegeYield;
    private RelativeLayout rl_bottom;
    private LinearLayout ll_offline_shop;
    private LinearLayout ll_privilege;
    private static final int requestFulsh = 990;
    private ImageView trumpet;

    private AnimationDrawable animationDrawable;
    private TextView mTv_persion;
    private String qqNum="2047537353";

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_main_home);
        getPersimmions();
        title = (RelativeLayout) findViewById(R.id.title);
        mTv_persion = (TextView) findViewById(R.id.tv_persion);
        TextView tvShopTitle = (TextView) findViewById(R.id.tvShopTitle);
        tvShopTitle.setText(R.string.app_name);
        rl_content = (RelativeLayout) findViewById(R.id.rl_content);
        iv_service = (ImageView) findViewById(R.id.iv_service);
        iv_unread_dot = (ImageView) findViewById(R.id.iv_dot);
//        ivLocation = (TextView) findViewById(R.id.ivLocation);
//        ivLocation.setText(MyApplication.getInstance().getCity());
        tvAd = (TextView) findViewById(R.id.tvAd);
        ll_yield_contain = (LinearLayout) findViewById(R.id.ll_yield_contain);
        rl_pricilege = (RelativeLayout) findViewById(R.id.rl_pricilege);
        tv_original = (TextView) findViewById(R.id.tv_original);
        rl_yield = (RelativeLayout) findViewById(R.id.rl_yield);
        tv_today = (TextView) findViewById(R.id.tv_today);
        tv_privilegeYield = (TextView) findViewById(R.id.tv_privilegeYield);

        ll_privilege = (LinearLayout) findViewById(R.id.ll_privilege);

        ll_offline_shop = (LinearLayout) findViewById(R.id.ll_offline_shop);
        rl_bottom = (RelativeLayout) findViewById(R.id.rl_bottom);

        trumpet = (ImageView) findViewById(R.id.trumpet_gif);

//        Glide.with(this).load(R.drawable.thumpet).asGif().into(trumpet);
        llUpGift = (LinearLayout) findViewById(R.id.llUpGift);
        tvNewTips = (TextView) findViewById(R.id.tvNewTips);
        //商城
        meibiShop = (LinearLayout) findViewById(R.id.meibiShop);
        bolivarShop = (LinearLayout) findViewById(R.id.bolivarShop);

        tvStoreHome = (TextView) findViewById(R.id.tvStoreHome);
        //设置高度
        flow = (FrameLayout) findViewById(R.id.flow);
        ImageUtils.setHeight(this, Constants.flowRate, flow);
        banner = (Banner) findViewById(R.id.banner);
    }

    @Override
    protected void initData() {
        super.initData();
        unsubscribe();
        mDisposable = Observable.concat(AddParameter.getInstance().getAdData(1), AddParameter.getInstance().getNewMessage(),
                AddParameter.getInstance().upDataVersion())
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(Disposable disposable) throws Exception {
//                        showProgressDialog();
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer() {
                    @Override
                    public void accept(Object o) throws Exception {
                        if (o instanceof AdResult) {
                            MyApplication.getInstance().setSpValue(((AdResult) o).getSafeobj());
                            data.clear();
                            if (((AdResult) o).getCode() == 1) {
                                data.addAll(((AdResult) o).getData());
                                lunbo();
                            } else {
                                ToastUtil.show(getString(R.string.loseData, ((AdResult) o).getCode()));
                            }
                        } else if (o instanceof NewMessage) {
                            MyApplication.getInstance().setSpValue(((NewMessage) o).getSafeobj());
                            if (((NewMessage) o).getCode() == 1) {
                                if (null != ((NewMessage) o).getData().getDescription() && !"".equals(((NewMessage) o).getData().getDescription())) {
                                    tvAd.setText(((NewMessage) o).getData().getDescription() + "                    " + ((NewMessage) o).getData().getDescription()+ "                    " + ((NewMessage) o).getData().getDescription());
                                    initAnimations();
                                }
                            } else {
                                ToastUtil.show(getString(R.string.loseData, ((NewMessage) o).getCode()));
                            }
                        } else if (o instanceof UpdateResult) {
                            MyApplication.getInstance().setSpValue(((UpdateResult) o).getSafeobj());
                            if (((UpdateResult) o).getCode() == 1) {
                                if (null != ((UpdateResult) o).getUpdClient() && !"".equals(((UpdateResult) o).getUpdClient())) {
                                    if (null != ((UpdateResult) o).getUpdClient().getDownUrl() && !"".equals(((UpdateResult) o).getUpdClient().getDownUrl())) {
                                        downFile();
                                    } else {
                                        isExists();
                                    }
                                } else {
                                    isExists();
                                }
                            } else {
                                ToastUtil.show(getString(R.string.loseData, ((NewMessage) o).getCode()));
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        dismessProgressDialog();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
//                        dismessProgressDialog();
                    }
                });
    }


    private void initAnimations() {
        animationDrawable = (AnimationDrawable) getResources().getDrawable(R.drawable.animation_trumpt);
        trumpet.setBackgroundDrawable(animationDrawable);
        animationStart();
    }

    private void animationStart() {
        if (animationDrawable != null && !animationDrawable.isRunning()) {
            animationDrawable.start();
        }
    }

    /**
     * 初始化数据
     */
    private void initInfo() {
        if (MyApplication.getInstance().isShareHolders()) {  //股东或会员且股点不为零到原始收益
            ll_privilege.setVisibility(View.VISIBLE);
            rl_yield.setVisibility(View.GONE);
        } else {
            ll_privilege.setVisibility(View.GONE);
            rl_yield.setVisibility(View.VISIBLE);
        }
    }

    private void lunbo() {
        //初始化轮播控件
        banner.isAutoPlay(true);
        banner.setDelayTime(3000);
        banner.setIndicatorGravity(BannerConfig.CENTER);
        List<String> images = new ArrayList<>();
        for (int i = 0; i < data.size(); i++) {
            images.add(Url.IMG_URL + data.get(i).getImage());
        }
        banner.setImages(images)
                .setImageLoader(new GlideImageLoader())
                .start();

        banner.setOnBannerListener(this);
    }

    @Override
    public void OnBannerClick(int position) {
        if (!TextUtils.isEmpty(data.get(position).getId())) {
            LunBoUtils.getInstance(this).lunBoItemClickListener(data.get(position).getId(), data.get(position).getIsvideo(), data.get(position).getUrl());
        }
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            //Glide 加载图片简单用法
            Glide.with(context).load(path).placeholder(R.mipmap.iv_loading).into(imageView);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        //开始轮播
        banner.startAutoPlay();
    }

    @Override
    protected void onStop() {
        super.onStop();
        //结束轮播
        banner.stopAutoPlay();
    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case SDK_PERMISSION_REQUEST:
                if (grantResults.length > 0) {
                    if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                        MyApplication.getInstance().mLocationClient.start();
//                    ivLocation.setText(MyApplication.getInstance().getCity());
                    } else {
                        // 没有获取到权限，做特殊处理
                    }
                }
                break;
            default:
                break;
        }
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }
        } else {
            return true;
        }
    }

    @Override
    protected void processSuccessResult(String response) throws JSONException {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("myinfo".equals(flag)) {
                MyInfo myInfo = gson.fromJson(response, MyInfo.class);
                MyApplication.getInstance().setSpValue(myInfo.getSafeobj());
                if (null != myInfo.getUserInfo() && !"".equals(myInfo.getUserInfo())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", "1".equals(myInfo.getUserInfo().getIsshareholders())).commit();
                }
                if (String.valueOf(myInfo.getSharesnum()) != null) {
                    MyApplication.getInstance().sharedPrefrences.edit().putInt("point", myInfo.getSharesnum()).commit();
                }
                if ((null != String.valueOf(myInfo.getInnernum()) && myInfo.getInnernum() > 0)
                        || (null != myInfo.getRedbeannum() && DataUtil.moreThanOtherNoEqual(myInfo.getRedbeannum(), "0"))) {
                    showGetBackSilverDialog(myInfo.getInnernum(), myInfo.getRedbeannum());
                }
                getUserInfo();
            } else if ("userinfo".equals(flag)) {
                UserExtendResult userExtendResult = gson.fromJson(response, UserExtendResult.class);
                MyApplication.getInstance().setSpValue(userExtendResult.getSafeobj());
                if (null != userExtendResult.getRedbean() && !"".equals(userExtendResult.getRedbean())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("hd", DataUtil.formatDataSixPoint(userExtendResult.getRedbean())).commit();
                }
                if (null != userExtendResult.getData() && !"".equals(userExtendResult.getData())) {
                    MyApplication.getInstance().sharedPrefrences.edit().putString("inner", userExtendResult.getData().getInnercurrency()).commit();
                    MyApplication.getInstance().sharedPrefrences.edit().putString("share", userExtendResult.getData().getSharesgains()).commit();
                }
                initInfo();
                getSharesgains();
            } else if ("today".equals(flag)) {
                TodayEarningResult result = gson.fromJson(response, TodayEarningResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (null != result.getRecode().getSharesgains() && !"".equals(result.getRecode().getSharesgains())) {

                    tv_original.setText(DataUtil.formatDataFivePoint(result.getRecode().getSharesgains()) + "元");
                } else {
                    tv_original.setText("0元");
                }
                getConsumegains();
            } else if ("todayConsuem".equals(flag)) {
                TodayConsumerYield todayConsumerYield = gson.fromJson(response, TodayConsumerYield.class);
                MyApplication.getInstance().setSpValue(todayConsumerYield.getSafeobj());
                if (null != todayConsumerYield.getPrevDayGains() && !"".equals(todayConsumerYield.getPrevDayGains())) {
                    tv_privilegeYield.setText(DataUtil.formatDataSixPoint(todayConsumerYield.getPrevDayGains()) + " 个");
                    SpannableString msp = new SpannableString(DataUtil.formatDataSixPoint(todayConsumerYield.getPrevDayGains()) + " 个");
                    msp.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC), 0, msp.length() - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    tv_today.setText(msp);
                } else {
                    tv_privilegeYield.setText(getString(R.string.sixZero, "个"));
                    tv_today.setText(getString(R.string.sixZero, "个"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取昨日股份收益
     */
    private void getSharesgains() {
        flag = "today";
        getServer(Url.MY_TODAY_EARNINGS, null, "", false, null, "get");
    }

    /**
     * 获取昨日消费收益
     */
    private void getConsumegains() {
        flag = "todayConsuem";
        getServer(Url.CONSUMER_TODAY_YIELD, null, "", false, null, "get");
    }


    /**
     * 活动返现
     *
     * @param backSilver
     * @param redbeannum
     */
    private void showGetBackSilverDialog(int backSilver, String redbeannum) {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        final AlertDialog dialog = adb.create();
        View view = View.inflate(this, R.layout.dialog_back_silver, null);
        ImageView ivCancle = (ImageView) view.findViewById(R.id.iv_back_cancle);
        TextView tv_HD_number = (TextView) view.findViewById(R.id.tv_HD_number);
        TextView tv_MD_number = (TextView) view.findViewById(R.id.tv_MD_number);

        if (backSilver > 0 && DataUtil.moreThanOtherNoEqual(redbeannum, "0")) {
            tv_HD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setVisibility(View.VISIBLE);
            tv_HD_number.setText(redbeannum + "  红豆");
            tv_MD_number.setText(backSilver + "  美豆");
        } else if (backSilver > 0 && !DataUtil.moreThanOtherNoEqual(redbeannum, "0")) {
            tv_HD_number.setVisibility(View.GONE);
            tv_MD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setText(backSilver + "  美豆");
        } else if (backSilver <= 0 && DataUtil.moreThanOtherNoEqual(redbeannum, "0")) {
            tv_HD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setVisibility(View.GONE);
            tv_HD_number.setText(redbeannum + "  红豆");
        } else {
            tv_HD_number.setVisibility(View.VISIBLE);
            tv_MD_number.setVisibility(View.VISIBLE);
            tv_HD_number.setText("0  红豆");
            tv_MD_number.setText("0  美豆");
        }
        TextView tvSure = (TextView) view.findViewById(R.id.tv_back_silver_sure);
        ivCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.setView(view);
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialogInterface, int keyCode, KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_BACK && keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                    return true;
                }
                return false;
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    private void getMyInfo() {
        flag = "myinfo";
        getServer(Url.MYINFO, null, "", false, null, "get");
    }


    /**
     * 是否需要更新
     */
    int version = 0;
    HttpURLConnection conn = null;

    private void isExists() {
        version = Integer.parseInt(MyApplication.getInstance().getMinVersion()) + 1;
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL(Url.APK_URL + version + Url.APK_URL_NAME);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(5000);
                    conn.connect();
                    if (conn.getResponseCode() == 200) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                downFile2();
                            }
                        });
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                finish();
                return true;
            } else {
                return false;
            }
        }
    };

    private void downFile() {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_version, null);
        ImageView iv_Cancel = (ImageView) view.findViewById(R.id.iv_Cancel);
        TextView tv_dsc = (TextView) view.findViewById(R.id.tv_dsc);
        TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        adb.setView(view);
        if (null != result.getUpdClient().getDesc() && !"".equals(result.getUpdClient().getDesc())) {
            tv_dsc.setText(result.getUpdClient().getDesc());
        } else {
            tv_dsc.setText("发现新版本，请尽快更新");
        }
        dialog = adb.create();
        dialog.setOnKeyListener(keylistener);
        dialog.setCanceledOnTouchOutside(false);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                System.exit(0);
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                downLoadApk();
            }
        });


        dialog.show();
    }

    private void downFile2() {
        AlertDialog.Builder adb = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_version, null);
        ImageView iv_Cancel = (ImageView) view.findViewById(R.id.iv_Cancel);
        TextView tv_dsc = (TextView) view.findViewById(R.id.tv_dsc);
        TextView tv_ok = (TextView) view.findViewById(R.id.tv_ok);
        adb.setView(view);
        tv_dsc.setText("发现新版本，请尽快更新");
        dialog = adb.create();
        Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setOnKeyListener(keylistener);
        dialog.setCanceledOnTouchOutside(false);
        iv_Cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                System.exit(0);
            }
        });
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                downLoadApk2();
            }
        });
        dialog.show();
    }

    private void downLoadApk2() {
        final ProgressDialog pd; //进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(1000);
        pd.setMessage("正在下载更新");
        pd.setOnKeyListener(keylistener);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d M/%2d M");
        pd.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = CommonTool.getFileFromServer(Url.APK_URL + version + Url.APK_URL_NAME, pd);

                    installApk(file);
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 下载APK
     */
    private void downLoadApk() {
        final ProgressDialog pd; //进度条对话框
        pd = new ProgressDialog(this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setProgress(1000);
        pd.setMessage("正在下载更新");
        pd.setOnKeyListener(keylistener);
        pd.setCanceledOnTouchOutside(false);
        pd.setProgressNumberFormat("%1d M/%2d M");
        pd.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File file = CommonTool.getFileFromServer(result.getUpdClient().getDownUrl(), pd);
                    installApk(file);
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //安装apk
    protected void installApk(File file) {
        if (file != null) {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                Uri apkUri = FileProvider.getUriForFile(context, context.getResources().getString(R.string.authorities), file);//在AndroidManifest中的android:authorities值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//添加这一句表示对目标应用临时授权该Uri所代表的文件
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                context.startActivity(install);
            } else {
                Intent intent = new Intent();
                //执行动作
                intent.setAction(Intent.ACTION_VIEW);
                //执行的数据类型
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        }
    }

    /**
     * 获取用户信息
     */
    private void getUserInfo() {
        flag = "userinfo";
        getServer(Url.MY_EXTEND_INFO, null, "", false, null, "get");
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try {
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
        } catch (Exception e) {
            e.getMessage();
        }
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        meibiShop.setOnClickListener(this);
        bolivarShop.setOnClickListener(this);
        tvStoreHome.setOnClickListener(this);
        tvNewTips.setOnClickListener(this);
        rl_content.setOnClickListener(this);
        llUpGift.setOnClickListener(this);
        rl_pricilege.setOnClickListener(this);
        ll_offline_shop.setOnClickListener(this);
        rl_yield.setOnClickListener(this);
        ll_yield_contain.setOnClickListener(this);
        rl_bottom.setOnClickListener(this);
        tvAd.setOnClickListener(this);
        mTv_persion.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        Intent intent = new Intent(context, MainActivity.class);
        switch (view.getId()) {
            case R.id.meibiShop:
                intent.putExtra("index", 0);
                startActivity(intent);
                break;
            case R.id.bolivarShop:
                intent.putExtra("index", 1);
                startActivity(intent);
                break;
            case R.id.ll_offline_shop:  //线下超市
                intent.putExtra("index", 2);
                startActivity(intent);
                break;
            case R.id.tv_persion:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    intent.putExtra("index", 3);
                    startActivity(intent);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.llUpGift:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    intent.putExtra("index", 4);
                    startActivity(intent);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.ll_yield_contain:
            case R.id.rl_yield:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {
                    startAct(ConsumerLoveYieldActivity.class);
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.tvStoreHome:
                startAct(SellerCenterActivity.class);
                break;
            case R.id.rl_bottom:
                if (null != MyApplication.getInstance().getUserId() && !"".equals(MyApplication.getInstance().getUserId())) {

                    AndPermission.with(context)
                            .requestCode(100)
                            .permission(Permission.CAMERA)
                            .callback(new PermissionListener() {
                                @Override
                                public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                    //跳到扫描二维码页面
                                    Intent payIntent = new Intent(context, CaptureActivity.class);
//                                    Intent payIntent = new Intent(context, QrTwoActivity.class);
                                    //startActivity(intent);
                                    //跳液面需要返回一个结果
                                    startActivityForResult(payIntent, MAINHOMEPAYMONEY);
                                }

                                @Override
                                public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {

                                }
                            })
                            .start();
                } else {
                    startAct(LoginActivity.class);
                }
                break;
            case R.id.rl_pricilege:
                startAct(MyDividendActivity.class);//原始收益
                break;
            case R.id.tvNewTips:
                startAct(NewTipsActivity.class);
                break;
            case R.id.tvAd:
                startAct(SystemMessageActivity.class);
                break;
            case R.id.rl_content:
                if (CommonTool.checkApkExist(MainHomeActivity.this,"com.tencent.mobileqq")){
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                            "mqqwpa://im/chat?chat_type=wpa&uin="+Constants.QQ_NUM+"&version=1")));
                }else {
                    showShortToast("未安装QQ");
                }

                break;
        }
    }



    @Override
    protected void onResume() {
        super.onResume();
        if (TextUtils.isEmpty(MyApplication.getInstance().getUserId())) {
            tv_today.setText("0个");
        }
        initInfo();  //为了退出登录之后的调用
        if (!TextUtils.isEmpty(MyApplication.getInstance().getUserId())) {
            getMyInfo();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == requestFulsh) {
            pw.dismiss();
        } else if (requestCode == requestFulshConver) {
            pw.dismiss();
        }
        if (resultCode == RESULT_OK) {
            String text = data.getStringExtra("text");
            String[] split = text.split("\\|\\|");
            if (split.length == 5 && ("1".equals(split[0]) || "2".equals(split[0])) && split[1].length() == 20
                    && DataUtil.isDouble(split[2]) && DataUtil.isGoodJson(split[3])) {
                Intent intent = new Intent(context, QrOrderActivity.class);
                intent.putExtra("codeinfo", text);
                startActivity(intent);
            } else if ("2".equals(split[0]) && split[1].length() == 20 && ("2".equals(split[2]) || "3".equals(split[2]))
                    && DataUtil.isDouble(split[3]) && DataUtil.isDouble(split[4])) {
                Intent mIntent = new Intent(UiUtils.getContext(), PayMoneyActivity.class);
                mIntent.putExtra("secret", split[5]);
                startActivity(mIntent);
            } else if ("3".equals(split[0])) {
                Intent intent = new Intent(context, RewardCoinDetailActivity.class);
                intent.putExtra("gid", split[1]);
                startActivity(intent);
            } else {
                showShortToast("无法识别该二维码");
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            MyApplication.getInstance().sharedPrefrences.edit().putString("beautifulcredentials", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardcoincredentials", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("MDChangecredentials", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("OffLinecredentials", "").commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 双击退出程序
     */
    long firstTime = 0;

    @Override
    public void onBackPressed() {
        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime < 2000) {
            super.onBackPressed();
        } else {
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            firstTime = System.currentTimeMillis();
        }
    }

}
